package com.itdfq.springboot_shrio.config;


import com.itdfq.springboot_shrio.pojo.Users;
import com.itdfq.springboot_shrio.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author GocChin
 * @Date 2021/6/6 15:29
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Descript:
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UsersService usersService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权=》doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        Users currentUser = (Users) subject.getPrincipal();//拿到User对象
        //从数据库中获取当前的权限，然后赋予当前用户的权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证》doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //从数据库中查询用户名，密码
        Users byUsername = usersService.findByUsername(userToken.getUsername());
        if (byUsername == null) {
            return null;  //抛出用户不存在异常
        }
        //获取登录对象
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",byUsername);

        //密码认证  shiro自己做
//        第一个参数 放user对象，方便上面的方法获取当前用户数据
        return new SimpleAuthenticationInfo(byUsername,byUsername.getPwd(),"root");

    }
}
